package ru.timofeyco.justfeelbetter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

import ru.timofeyco.justfeelbetter.adapters.SelectTypesAdapter;
import ru.timofeyco.justfeelbetter.db.JustFeelBetterDatabase;
import ru.timofeyco.justfeelbetter.model.Drill;
import ru.timofeyco.justfeelbetter.model.DrillType;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddDrillActivity extends Activity {
	JustFeelBetterDatabase dbHelper;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_drill);
     
        dbHelper = new JustFeelBetterDatabase(this);
        DrillType[] drillTypes = dbHelper.getDrillTypes();        
        
        ArrayList<DrillType> drillTypesList = new ArrayList<DrillType>(Arrays.asList(drillTypes));
        SelectTypesAdapter drillTypesAdapter = new SelectTypesAdapter(this, R.layout.drill_type_edit_element, drillTypesList);
        
        Spinner drillTypesSpinner = (Spinner)findViewById(R.id.drillTypesSpinner);
        drillTypesSpinner.setAdapter(drillTypesAdapter);
    }
	
	public void onAddDrill(View v) throws IOException {
		EditText countTextEdit = (EditText)findViewById(R.id.countEdit);
		int count = 0;
		try {
			count = Integer.valueOf(countTextEdit.getText().toString());
		} catch(Exception ex) {
			Toast.makeText(this, getString(R.string.enter_number_for_adding), Toast.LENGTH_LONG).show();
			this.finish();
		}
		Spinner drillTypesSpinner = (Spinner)findViewById(R.id.drillTypesSpinner);
		DrillType type = (DrillType)drillTypesSpinner.getSelectedItem();
		Drill newDrill = new Drill(type, count, new Date(Calendar.getInstance().getTimeInMillis()));
		dbHelper.insertDrill(newDrill);
		
		dbHelper.close();
		this.finish();
	}
	
	public void onCancelDrill(View v) {
		dbHelper.close();
		this.finish();
	}
}
